package cn.windy.samary.module.abstracts;

import cn.windy.samary.core.exception.CustomException;
import cn.windy.samary.utils.ResourceBundleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * controller层异常全局处理
 *
 * @author zyl
 * @date 2018/3/2 9:43
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public Map handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Map<String, Object> map = new HashMap<>();

        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> errors = bindingResult.getAllErrors();
        return map;
    }


    /**
     * 处理入参绑定验证异常
     *
     * @param e
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BindException.class)
    public Map handleBindException(BindException e, WebRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        HttpServletRequest req = (HttpServletRequest) ((ServletWebRequest) request).getNativeRequest();
        String contextPath = req.getServletPath();
        for (ObjectError error : allErrors) {
            map.put("code", 599);
            map.put("msg", map.get("msg") == null ? error.getDefaultMessage() : map.get("msg") + ";" + error.getDefaultMessage());
        }

        logger.error(map.toString());
        logger.error(e.getMessage(), e);
        return map;
    }

    /**
     * 处理缺少参数异常
     *
     * @param e ..
     * @return .
     */
    @ResponseBody
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Map<String, Object> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 599);
        map.put("msg", e.getParameterName() + ResourceBundleUtil.getMessage("parameter.miss"));
        logger.error(map.toString());
        logger.error(e.getMessage(), e);
        return map;
    }


    //NumberFormatException
    @ResponseBody
    @ExceptionHandler(NumberFormatException.class)
    public Map<String, Object> handleNumberFormatException(NumberFormatException e) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", e.getMessage());
        return map;
    }

    //CustomException
    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public Map handleBindException(CustomException e, WebRequest request, HttpServletResponse response) {
        e.printStackTrace();
        logger.error(e.getMessage(), e);
        Map<String, Object> map = new HashMap<>();
        HttpServletRequest req = (HttpServletRequest) ((ServletWebRequest) request).getNativeRequest();
        String contextPath = req.getServletPath();
        map.put("code", 602);
        map.put("msg", e.getMessage());
        return map;
    }

    //EmptyResultDataAccessException
    @ResponseBody
    @ExceptionHandler(EmptyResultDataAccessException.class)
    public Map handleEmptyResultDataAccessException(EmptyResultDataAccessException e, WebRequest request, HttpServletResponse response) {
        e.printStackTrace();
        logger.error(e.getMessage(), e);
        Map<String, Object> map = new HashMap<>();

        HttpServletRequest req = (HttpServletRequest) ((ServletWebRequest) request).getNativeRequest();
        String contextPath = req.getServletPath();
        map.put("code", 602);
        map.put("msg", e.getMessage());

        return map;
    }

    @ResponseBody
    @ExceptionHandler(NullPointerException.class)
    public Map<String, Object> handleNullPointerException(NullPointerException e) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", e.getMessage());
        logger.error(map.toString());
        logger.error(e.getMessage(), e);
        return map;
    }


    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public Map<String, Object> handleInvalidRequestError(RuntimeException e) {
        logger.error(e.getMessage(), e);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", e.getMessage());
        return map;
    }

    @ResponseBody
    @ExceptionHandler(DataAccessException.class)
    public Map<String, Object> handleInvalidRequestError(DataAccessException e) {
        logger.error(e.getMessage(), e);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", e.getMessage());
        return map;
    }

    /**
     * 入参类型不匹配异常
     *
     * @param e 入参类型不匹配异常
     * @return map
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Map<String, Object> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 599);
        map.put("msg", e.getName() + ResourceBundleUtil.getMessage("parameter.type.error") + e.getRequiredType());
        logger.error(map.toString());
        logger.error(e.getMessage(), e);
        return map;
    }

    @ResponseBody
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public Map<String, Object> handleUnexpectedServerError(NoHandlerFoundException e, WebRequest request, HttpServletResponse response) {

        Map<String, Object> map = new HashMap<>();
        map.put("code", 404);
        map.put("msg", e.getMessage());
        return map;
    }

}
